package com.gogowan.agroenterprise.widget;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.VideoInfo;
import com.gogowan.agroenterprise.utils.Utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class OperationVideosAdapter extends BaseAdapter {

	private List<VideoInfo> list;
	private Context context;
	//private AnonymousLoginResultInfo anonymousLoginResultInfo;
	private List<Drawable> listDrawable;
	private String path;
	private GridView gridView;

	public OperationVideosAdapter(Context context, List<VideoInfo> list
			,GridView gridView) {
		this.context = context;
		this.gridView = gridView;
		setList(list);
		listDrawable = new ArrayList<Drawable>();
		
	}

	public void setList(List<VideoInfo> list) {
		if (list != null) {
			this.list = list;
			this.list.add(null);
		} else {
			this.list = new ArrayList<VideoInfo>();
			this.list.add(null);
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			VideoInfo picturesInfo = list.get(i);
			if (picturesInfo != null) {
				listDrawable.add(i, null);
				Drawable drawable = Drawable.createFromPath(path) ;
				listDrawable.set(i,drawable);
				OperationVideosAdapter.this.notifyDataSetChanged();
			}
		}
		// this.notifyDataSetChanged();
	}
	
	public List<VideoInfo> getDataList() {
		List<VideoInfo> list = this.list;
		if (list.size() == 0) {
			
		} else {
			list.remove(list.size() - 1);
		}
		return list;
	}
	
	public List<VideoInfo> getList() {
		return this.list;
	}

	/**
	 * 添加
	 * 
	 * @param picturesInfo
	 */
	public void addVideoInfo(VideoInfo picturesInfo) {
		if (list.size()>6) {
			Toast.makeText(context, "不能添加更多视频", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (list != null) {
			// list最后一条空的赋值
			if(list.size() == 0){
				list.add(null);
			}
			list.set(list.size() - 1, picturesInfo);
			list.add(null);
			// 先获取图片，在刷新
			if (picturesInfo != null) {
				path = "/mnt/sdcard/AgricultureSystem/Video/"+picturesInfo.getImageurl();
				Drawable drawable = Drawable.createFromPath(path) ;
				if (drawable != null) {
					listDrawable.add(list.size() - 2, null);
					listDrawable.set(list.size() - 2,drawable);
					// handler.sendEmptyMessage(1);
					OperationVideosAdapter.this.notifyDataSetChanged();
				}
			}
			// this.notifyDataSetChanged();
		}
	}

	/**
	 * 删除一个
	 * 
	 * @param position
	 */
	public boolean del(int position) {
		try {
			list.remove(position);
			listDrawable.remove(position);
			this.notifyDataSetChanged();
		} catch (IndexOutOfBoundsException e) {
			// TODO: handle exception
			return false;
		} catch (UnsupportedOperationException e) {
			// TODO: handle exception
			return false;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}

	@Override
	public int getCount() {
		if (list != null) {
			return list.size();
		}
		return 0;
	}

	@Override
	public VideoInfo getItem(int position) {
		if (list != null) {
			return list.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			convertView = (View) inflater.inflate(
					R.layout.pictures_grid_view_item, null);

			holder = new ViewHolder();
			holder.img = (ImageView) convertView
					.findViewById(R.id.pictures_gridview_item_image);
			holder.progressBar = (ProgressBar) convertView
					.findViewById(R.id.pictures_gridview_item_pb);
			holder.text = (TextView) convertView
			.findViewById(R.id.pictures_gridview_item_text);
			//holder.text.setFilters(new InputFilter[]{new InputFilter.LengthFilter(245)}); 
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		// layout.setClickable(false);
		if (list != null && list.size() > 0&&listDrawable!=null&&listDrawable.size()>0) {
			VideoInfo picturesInfo = list.get(position);
			if (picturesInfo != null && !Utils.isEmpty(picturesInfo.getImageurl())) {
				try {
					Drawable drawable = listDrawable.get(position);
					if (drawable != null) {
						holder.img.setImageDrawable(drawable);
					}else
					{
						holder.img.setImageDrawable(null);
					}
					holder.text.setText(picturesInfo.getDescription());
				} catch (Exception e) {
					Log.d("setText", e.getLocalizedMessage());
				}
				
			} else {
				final LayoutInflater inflater = LayoutInflater.from(context);
				convertView = (View) inflater.inflate(
						R.layout.pictures_grid_view_item, null);

				holder = new ViewHolder();
				holder.img = (ImageView) convertView
						.findViewById(R.id.pictures_gridview_item_image);
				holder.progressBar = (ProgressBar) convertView
						.findViewById(R.id.pictures_gridview_item_pb);
				convertView.setTag(holder);
				holder.text = (TextView) convertView
						.findViewById(R.id.pictures_gridview_item_text);
				if(picturesInfo == null)
				{
				   holder.img.setBackgroundResource(android.R.color.transparent);
//				   holder.img.setImageResource(R.drawable.hs_image_paizhao);
				}
			}
		}else
		{
			holder.img.setBackgroundResource(android.R.color.transparent);
		}
		adaptHeight();
		return convertView;
	}
	public void adaptHeight()
	{
		try {
			int height=Integer.parseInt(context.getString(R.string.grid_view_height));
			//int height = 120;
			//自适应gridview高度
			int h=(list.size()-1)/4+1;//计算行数
			LayoutParams param=gridView.getLayoutParams();
			param.height=height*h;//设置固定高
			gridView.setLayoutParams(param);
		}catch(NumberFormatException nfe)
		{
			// TODO: handle exception
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	static class ViewHolder {
		ImageView img;
		ProgressBar progressBar;
		TextView text;
	}

	/**
	 * 获取图片并显示
	 * 
	 * @author Administrator
	 * 
	 */
	public class GetPicAsync extends MyAsyncTask {
		private int location;
		private Drawable drawable = null;
		public GetPicAsync(int location)
		{
			this.location=location;
			listDrawable.add(location, null);
		}
		@Override
		protected Object doInBackground(Object... params) {
			
			try {
				String path = (String) params[0];
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestMethod("GET");
				InputStream inStream = conn.getInputStream();
				if (conn.getResponseCode() == 200) {
					drawable = Drawable.createFromStream(inStream, path);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object res) {
			try {
			   //Drawable drawable = (Drawable) res;
			   if(drawable!=null)
			   {
			      listDrawable.set(location,drawable);
				  OperationVideosAdapter.this.notifyDataSetChanged();
			   }else
			   {
				   Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT).show();
				   try {
						del(list.size()-2);
					} catch (Exception e) {
						// TODO: handle exception
					}
			   }
			} catch (Exception e) {
				 Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT).show();
				 try {
						del(list.size()-2);
					} catch (Exception e2) {
						// TODO: handle exception
					}
			}
			super.onPostExecute(null);
		}

	}
	
	public void clear() {
		list.clear();
		this.list = new ArrayList<VideoInfo>();
		this.list.add(null);
		this.notifyDataSetChanged();
	}

}